<template>
  <el-card shadow='never'
           class="filter-component"
           :class="Boolean(scriptItem.hideBorder) ? 'hide-border' : ''">
    <el-form>
      <el-form-item>
        <div style="display: flex;align-items: center;position:relative;height:48px;padding:8px 0;">
          <el-radio-group v-model="dataSource[scriptItem.text][scriptItem.condition]"
                          :disabled="dataSource[scriptItem.text][scriptItem.dataArr].length<2"
                          @change="elRadioGroupChange"
                          size="small">
            <el-radio-button label="and"
                             @click="condition('and')">AND</el-radio-button>
            <el-radio-button label="or" v-if="nextTicketType.replace('dataset','')  !== 'syncro'"
                             @click="condition('or')">OR</el-radio-button>
          </el-radio-group>
          <el-popover placement="bottom"
                      width="171"
                      v-model="addCondition"
                      popper-class='filter-add-group-popover'
                      trigger="hover">
            <div class="cuifont icon_add_circle iconfont-normal"
                 style="margin-left:20px;"
                 slot="reference"></div>
            <div class="add-group-item"
                 @click="addRow('grp','')">
              <div class="cuifont icon_add"
                   style="display:inline-flex;fontSize:14px;margin-right:10px;"
                   slot="reference"></div>
              Add Group
            </div>
            <div class="add-group-item"
                 @click="addRow('row','')">
              <div class="cuifont icon_add"
                   style="display:inline-flex;fontSize:14px;margin-right:10px;"
                   slot="reference"></div>
              Add Condition
            </div>
          </el-popover>
          <div class="test">
            <el-tooltip v-if="!$attrs.optionsId || !$attrs.searchIdentifier || !ruleForm.displayName || !ruleForm.params.points"
                        :open-delay="1000"
                        content="Please select a filter and user on the top of the screen to run the rule test."
                        placement="top"
                        effect="dark">
              <div @click.stop
                    class="btn_gp"
                    v-if="$hasPermission('sys:settings:test')">
                <el-button @click="testHandlerForCustomRule" style="margin-right:8px"
                            :disabled="!$attrs.optionsId || !$attrs.searchIdentifier || !ruleForm.displayName || !ruleForm.params.points"
                            type="text"
                            icon="cuifont icon_eye_show"
                            size="mini">
                </el-button>
  
              </div>
            </el-tooltip>
            <el-tooltip v-else v-delTabIndex
                        class="item"
                        effect="dark"
                        :open-delay="1000"
                        content="Save & Test this rule"
                        placement="top">
              <div @click.stop
                    class="btn_gp"
                    v-if="$hasPermission('sys:settings:test')"
                    style="margin-left:8px">
                <i @click="testHandlerForCustomRule" class="cuifont icon_eye_show iconfont-normal"></i>
              </div>
            </el-tooltip>
          </div>
          <!-- <el-tooltip :open-delay="1000" effect="dark"
                      :content="$t('custom.filterinspector')"
                      placement="top">
            <div v-if="$hasPermission('sys:widget:moreedit')"
                 class="cuifont icon_filter_inspector iconfont-normal parse-filter"
                 @click="parseFilter"></div>
          </el-tooltip> -->
          <el-popover placement="bottom" ref="deletePop"
                      width="225"
                      trigger="click" v-model="clearAllPopover">
            <div style="word-break:break-word;text-align:left;">{{ $t('custom.clearFilterConditionTips') }}</div>
            <el-button type="danger"
                       size="small"
                       style="width:100%;padding:7px 10px;margin-top:10px;"
                       @click="clearFilter">{{ $t('custom.clearAll') }}</el-button>
            <div
                 class="cuifont icon_delete iconfont-normal clear-filter"
                 slot="reference"></div>
          </el-popover>
        </div>
        <div class="out-column-line">
          <div v-for="(filterItem,index) in dataSource[scriptItem.text][scriptItem.dataArr]"
               :key="`${index}-filter`"
               class=""
               style="margin-left:30px;">
            <div v-if="!filterItem[scriptItem.condition]"
                 class="filterRow item-line">
              <el-row :gutter="10"
                      :class="{
                        'header-item': index === 0 || (index > 0 && dataSource[scriptItem.text][scriptItem.dataArr][index - 1][scriptItem.dataArr]&&dataSource[scriptItem.text][scriptItem.dataArr][index - 1][scriptItem.dataArr].length > 0),
                        'center-item': 0 < index && index < dataSource[scriptItem.text][scriptItem.dataArr].length - 1,
                        'footer-item': (index === dataSource[scriptItem.text][scriptItem.dataArr].length - 1) || (index < dataSource[scriptItem.text][scriptItem.dataArr].length - 1 && dataSource[scriptItem.text][scriptItem.dataArr][index + 1][scriptItem.dataArr]&&dataSource[scriptItem.text][scriptItem.dataArr][index + 1][scriptItem.dataArr].length > 0)
                      }"
                      style="padding: 8px 10px;background: #F0F0F0;border-radius: 4px;margin-left:0;margin-right:0;"
                      :style="{borderRadius: index === 0 ? '4px 4px 0 0' : index === dataSource[scriptItem.text][scriptItem.dataArr].length - 1 ? '0 0 4px 4px' : '0' }">
                <el-col
                        :span="5"
                        style="padding-right:5px;padding-left:0;">
                  <span style="display: inline-block;"
                        :style="{ width: scriptItem.keyLabelWidth }">{{scriptItem.keyLabel}}</span>
                  <el-select :style="{ width: scriptItem.keyFieldsWidth }"
                             v-model="filterItem[scriptItem.keyFields]"
                             filterable
                             :disabled="filterItem.conditionDisabled"
                             default-first-option
                             @change="setType($event, filterItem)"
                             :placeholder="scriptItem.keyHint">
                    <el-option v-for="(item,jj) in scriptItem[scriptItem.keyOptions]"
                               :key="jj"
                               :label="item.label"
                               :value="item.value">
                      <DataTypeIcon :dataTypeObj="item"></DataTypeIcon>
                    </el-option>
                  </el-select>
                </el-col>
                <template v-if='filterItem[scriptItem.keyFields]'>
                  <el-col
                          :span="5">
                    <span style="display: inline-block;"
                          :style="{ width: scriptItem.optionLabelWidth }">{{ scriptItem.optionLabel }}</span>
                    <el-select :style="{ width: scriptItem.optionFieldsWidth }"
                               v-model="filterItem[scriptItem.optionFields]"
                               filterable
                               clearable
                               @change="changeHander($event, filterItem)"
                               default-first-option
                               :placeholder="scriptItem.optionHint">
                      <el-option v-for="(o,ii) in optionsFilter(filterItem.type,filterItem)"
                                 :key="ii"
                                 :value="o.value"
                                 :label="o.label">
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="9">
                    <span style="display: inline-block;float: left;"
                          :disabled="valueFieldDisabled(filterItem[scriptItem.optionFields])"
                          :style="{ width: scriptItem.valueLabelWidth }">
                    </span>
                    <TypeFilterTemplate :key="filterItem[scriptItem.optionFields]"
                                        :rowIndex="index+''"
                                        :isRemoteObject="isRemoteObject"
                                        :gadgetSetting="gadgetSetting"
                                        :filterType='filterItem.type'
                                        :dataForm="dataSource"
                                        :nextTicketType="nextTicketType"
                                        :allValueList="allValueList"
                                        @changeValue='changeValue'
                                        :scriptItem="scriptItem"></TypeFilterTemplate>
                  </el-col>
                  <el-col :span="scriptItem.valueTypeFieldsWidth === '0' ? 0 : 4">
                    <span style="display: inline-block;"
                          :style="{ width: scriptItem.valueTypeLabelWidth }">{{scriptItem.valueTypeLabel}}</span>
                    <el-select :style="{ width: scriptItem.valueTypeFieldsWidth }"
                               v-model="filterItem[scriptItem.valueTypeFields]"
                               :placeholder="scriptItem.valueTypeHint">
                      <el-option v-for="(oo,ii) in scriptItem.valueTypeList"
                                 :key="ii"
                                 :value="oo"
                                 :label="oo">
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="2"
                          v-if="(scriptItem.IsSlicer?scriptItem.IsSlicer:false)">
                      <el-checkbox label="Slicer"
                                  :disabled="valueFieldDisabled(filterItem[scriptItem.optionFields])"
                                  @change="changeSlicerStatus(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus])"
                                  v-model='filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus]'></el-checkbox>
                  </el-col>
                  <el-col :span="4"
                          v-if="(scriptItem.IsSlicer?scriptItem.IsSlicer:false)&&
                        filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus] === true">
                    <div class="elcascader">
                          <el-popover ref="selectSlicerForm"
                              placement="bottom"
                              width="280"
                              trigger="click"
                              style="z-index:2019;display:block;float:left">
                                  <div>
                            <div style="display: flex;align-items: center;justify-content: space-between;height:25px;"
                                 v-if="!filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <span style="font-weight:bold;font-size: 16px;">Slicer</span>
                                <el-button style="float:right;font-size:12px;"
                                           type="text"
                                           @click="newAdvance(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus])">{{$t('custom.component.columns.advance')}}</el-button>
                            </div>
                            <div style="display: flex;align-items: center;justify-content: end;height:25px;"
                                 v-if="filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <i class="cuifont icon_chevron_lift"
                                   style="font-size:10px;padding-right:10px;"
                                   @click="advancedChange(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus])"></i>
                                <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.advance')}}</span>
                            </div>
                        </div>
                        <el-divider style="margin-top:15px;margin:10px 0;"></el-divider>
                              <div v-if="!filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <el-cascader popper-class="elcascader"
                                   v-model="filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsId]"
                                   :options="slicerList"
                                   filterable
                                   clearable
                                   :filter-method="dataFilter"
                                   :props="{ expandTrigger: 'hover',emitPath:false }"
                                   @change="changeSlicerItem(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsId])"></el-cascader>
                             </div>
                              <div v-if="filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <el-input v-model="filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrent]" @change="currentChangeSlice(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrent])" placeholder=""></el-input>
                              </div>
                              <div style="margin-top:5px;">
                                <span style="display: inline-block;margin-bottom:5px;">Ignore this filter if slicer not existed in the report</span>
                                  <el-checkbox style="margin-left:5px;"
                                         @change="changeSlicerIgnore(filterItem,filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsIgnoreFilter])"
                                         v-model='filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsIgnoreFilter]'>Ignore Filter</el-checkbox>
                              </div>
                              <div slot="reference">
                                    <el-input :readonly="true" style="width: 90%;" v-model="filterItem[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsName]" :disabled="valueFieldDisabled(filterItem[scriptItem.optionFields])"></el-input>
                              </div>
                      </el-popover>
                    </div>
                  </el-col>
                </template>
                <el-col :span="1"
                        style="display:flex;align-items:center;height:32px;">
                  <div class="cuifont icon_dismiss_circle_o iconfont-normal-line"
                  v-if="!filterItem.defaultCondition"
                       @click="deleteRow(index,'addData','')"></div>
                </el-col>
              </el-row>
            </div>
            <!--*************************************************************************-->
            <div :class="{ 'hide-out-column-line': index === dataSource[scriptItem.text][scriptItem.dataArr].length - 1 }">
              <div class="item-line"
                   style="display: flex;height:48px;padding:8px 0;align-items: center;"
                   v-if="filterItem[scriptItem.dataArr]&&filterItem[scriptItem.dataArr].length>0">
                <el-radio-group v-model="filterItem.condition"
                                :disabled="filterItem[scriptItem.dataArr].length<2"
                                size="small">
                  <el-radio-button label="and">AND</el-radio-button>
                  <el-radio-button label="or">OR</el-radio-button>
                </el-radio-group>
                <div class="cuifont icon_add_circle iconfont-normal"
                     style="margin-left:20px;"
                     @click="addRow('child',index)"></div>
                <div class="cuifont icon_dismiss_circle_o iconfont-normal"
                     @click="deleteRow(index,'addData','')"></div>
              </div>
              <template v-if="filterItem[scriptItem.dataArr]">
                <div class="in-column-line">
                  <div style="margin-left:30px;"
                       class="item-line"
                       v-for="(grpRow,indexs) in filterItem[scriptItem.dataArr]"
                       :key="`${indexs}-grp`">
                    <div style="padding: 8px 10px;background: #F0F0F0;"
                         :class="{
                                'header-item': indexs === 0,
                                'center-item': 0 < indexs && indexs < filterItem[scriptItem.dataArr].length - 1,
                                'footer-item': indexs === filterItem[scriptItem.dataArr].length - 1
                                }">
                      <el-row :gutter="10"
                              style="margin-left:0;margin-right:0;">
                        <el-col :span="5"
                                style="padding-right:5px;padding-left:0;">
                          <span style="display: inline-block;"
                                :style="{ width: scriptItem.keyLabelWidth }">{{ scriptItem.keyLabel }}</span>
                          <el-select :style="{ width: scriptItem.keyFieldsWidth }"
                                     v-model="grpRow[scriptItem.keyFields]"
                                     filterable
                                     @change="setType($event, grpRow)"
                                     default-first-option
                                     :placeholder="scriptItem.keyHint">
                            <el-option v-for="(item,jk) in nextTicketType==='autotask'?scriptItem[scriptItem.keyOptions]:scriptItem[scriptItem.keyOptions].filter(i=>i.label !=='Status' &&i.label !=='Service Board')"
                                       :key="jk"
                                       :label="item.label"
                                       :value="item.value">
                              <DataTypeIcon :dataTypeObj="item"></DataTypeIcon>
                            </el-option>
                          </el-select>
                        </el-col>
                        <template v-if="grpRow[scriptItem.keyFields]">
                          <el-col :span="5">
                            <span style="display: inline-block;"
                                  :style="{ width: scriptItem.optionLabelWidth }">{{ scriptItem.optionLabel }}</span>
                            <el-select :style="{ width: scriptItem.optionFieldsWidth }"
                                       v-model="grpRow[scriptItem.optionFields]"
                                       filterable
                                       clearable
                                       @change="changeHander($event, grpRow)"
                                       default-first-option
                                       :placeholder="scriptItem.optionHint">
                              <el-option v-for="(o,ii) in optionsFilter(grpRow.type,grpRow)"
                                         style="width: 88%;"
                                         :key="ii"
                                         :value="o.value"
                                         :label="o.label">
                              </el-option>
                            </el-select>
                          </el-col>
                          <el-col :span="9">
                            <span style="display: inline-block;float: left;"
                                  :disabled="valueFieldDisabled(grpRow[scriptItem.optionFields])"
                                  :style="{ width: scriptItem.valueLabelWidth }">
                              <!-- {{ scriptItem.valueLabel }} -->
                            </span>
                            <TypeFilterTemplate :gadgetSetting="gadgetSetting"
                                                :key="grpRow[scriptItem.optionFields]"
                                                :isRemoteObject="isRemoteObject"
                                                :rowIndex="indexs+'_'+index"
                                                :filterType='grpRow.type'
                                                :dataForm="dataSource"
                                                :nextTicketType="nextTicketType"
                                                :allValueList="allValueList"
                                                @changeValue='changeValue'
                                                :scriptItem="scriptItem"></TypeFilterTemplate>
                          </el-col>
                          <el-col :span="scriptItem.valueTypeFieldsWidth === '0' ? 0 : 3">
                            <span style="display: inline-block;"
                                  :style="{ width: scriptItem.valueTypeLabelWidth }">{{ scriptItem.valueTypeLabel }}</span>
                            <el-select :style="{ width: scriptItem.valueTypeFieldsWidth }"
                                       v-model="grpRow[scriptItem.valueTypeFields]"
                                       :placeholder="scriptItem.valueTypeHint">
                              <el-option v-for="(oo,ii) in scriptItem.valueTypeList"
                                         :key="ii"
                                         :value="oo"
                                         :label="oo">
                              </el-option>
                            </el-select>
                          </el-col>
                          <el-col :span="2"
                                  v-if="scriptItem.IsSlicer?scriptItem.IsSlicer:false">
                            <el-checkbox label="Slicer"
                                          :disabled="valueFieldDisabled(grpRow[scriptItem.optionFields])"
                                         @change="changeSlicerStatus(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus])"
                                         v-model='grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus]'></el-checkbox>
                          </el-col>
                          <el-col :span="4"
                                  v-if="(scriptItem.IsSlicer?scriptItem.IsSlicer:false)&&grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsStatus] === true">
                            <div class="elcascader">
                            <el-popover ref="selectSlicerForm"
                              placement="bottom"
                              width="280"
                              trigger="click"
                              style="z-index:2019;display:block;float:left">
                                  <div>
                            <div style="display: flex;align-items: center;justify-content: space-between;height:25px;"
                                 v-if="!grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <span style="font-weight:bold;font-size: 16px;">Slicer</span>
                                <el-button style="float:right;font-size:12px;"
                                           type="text"
                                           @click="newAdvance(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus])">{{$t('custom.component.columns.advance')}}</el-button>
                            </div>
                            <div style="display: flex;align-items: center;justify-content: end;height:25px;"
                                 v-if="grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <i class="cuifont icon_chevron_lift"
                                   style="font-size:10px;padding-right:10px;"
                                   @click="advancedChange(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus])"></i>
                                <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.advance')}}</span>
                            </div>
                        </div>
                        <el-divider style="margin-top:15px;margin:10px 0;"></el-divider>
                              <div v-if="!grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <el-cascader popper-class="elcascader"
                                   v-model="grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsId]"
                                   :options="slicerList"
                                   filterable
                                   clearable
                                   :filter-method="dataFilter"
                                   :props="{ expandTrigger: 'hover',emitPath:false }"
                                   @change="changeSlicerItem(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsId])"></el-cascader>
                             </div>
                              <div v-if="grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrentStatus]">
                                <el-input v-model="grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrent]" @change="currentChangeSlice(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsCurrent])" placeholder=""></el-input>
                              </div>
                               <div style="margin-top:5px;">
                                <span style="display: inline-block;margin-bottom:5px;">Ignore this filter if slicer not existed in the report</span>
                                  <el-checkbox style="margin-left:5px;"
                                         @change="changeSlicerIgnore(grpRow,grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsIgnoreFilter])"
                                         v-model='grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsIgnoreFilter]'>Ignore Filter</el-checkbox>
                              </div>
                              <div slot="reference">
                                <el-input :readonly="true" style="width: 90%;" v-model="grpRow[scriptItem.slicerFieldsObj][scriptItem.slicerFieldsName]" :disabled="valueFieldDisabled(grpRow[scriptItem.optionFields])"></el-input>
                              </div>
                      </el-popover>
                            </div>
                          </el-col>
                        </template>
                        <el-col :span="1"
                                style="display:flex;align-items:center;height:32px;">
                          <div class="cuifont icon_dismiss_circle_o iconfont-normal-line"
                               @click="deleteRow(indexs,'grpData',index)"></div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import TypeFilterTemplate from './advanced-filter-template'
import { generalConvertJsonToSQL } from '@/utils/common'
import { debounce } from 'lodash'
import DataTypeIcon from '@/components/script-render/components/data-type-icon'
export default {
  components: { TypeFilterTemplate, DataTypeIcon },
  mixins: [mixinTypeViewModule],
  // inject: ['botInfo'],
  props: {
    conditionFieldList: {
      type: Array,
      default: () => {
        return []
      }
    },
    originDataId: {
      type: String,
      default: ''
    },
    originDataType: {
      type: String,
      default: 'widget'
    },
    nextTicketType: {
      type: String,
      default: ''
    },
    gadgetSetting: {
      type: Object,
      default: () => {
        return {}
      }
    },
    customFieldList: {
      type: Array,
      default:()=>{
        return []
      }
    },
    ruleForm: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      dateValue: '',
      num: 1,
      cronPopover: false,
      btnCrect: null,
      keyList: [],
      grpindex: 0,
      dataSource: {},
      parseFilterLoading: false,
      slicerList: [],
      addCondition: false,
      clearAllPopover: false,
      allValueList: {},
      originDataIdForBot: null,
      originDataTypeForBot: null,
      conditionFormatOptions: [ { 'type': 'number', 'label': '=', 'value': '==' }, { 'type': 'number', 'label': '>', 'value': '>' }, { 'type': 'number', 'label': '>=', 'value': '>=' }, { 'type': 'number', 'label': '<', 'value': '<' }, { 'type': 'number', 'label': '<=', 'value': '<=' }, { 'type': 'number', 'label': '!=', 'value': '!=' } ],
      switch: false,
      isRemoteObject:{}
    }
  },
  watch: {
    dataForm: {
      handler: function (val) {
        this.dataSource = val
        if (this.scriptItem.hasSqlOutput) {
          val[this.scriptItem.sqlText] = generalConvertJsonToSQL(val[this.scriptItem.text])
        }
      },
      deep: true,
      immediate: true
    },
    comBotOriginData (val) {
      if (val) {
        this.initBotOriginData(val, this.$store.state.bot.type)
      }
    }
  },
  created () {
    let _self = this
    _self.initBotOriginData(_self.$store.state.bot.id, _self.$store.state.bot.type)
    _self.observer.rss('updateKeyArray', function (param) {
      _self.setKeyList(param)
    })
    this.$root.eventBus.$on('filterPreviewDialogUpdateFilter', () => {
      this.$emit('preViewFilter', this.dataSource)
    })
    _self.observer.rss('clearFilterData', function () {
      _self.clearData()
    })
    _self.getSlicerInfoList()
    _self.waitDataSourceInit()
  },
  computed: {
    comBotOriginData () {
      return this.$store.state.bot.id
    }
  },
  methods: {
    deletePopClose () {
      if (this.$refs.deletePop) {
        this.$refs.deletePop.doClose()
      }
    },
    dataFilter (node, keyword) {
      return node.text.toLowerCase().indexOf(keyword.toLowerCase()) !== -1
    },
    changeSlicerIgnore (data, val) {
      if (!val) {
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsIgnoreFilter] = false
      }
      data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsIgnoreFilter] = val
      this.$forceUpdate()
    },
    newAdvance (data, val) {
      if (!val) {
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = []
      }
      data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = !val
      this.$forceUpdate()
    },
    advancedChange (data, val) {
      if (val) {
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = null
      }
      data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = !val
      this.$forceUpdate()
    },
    changeSlicerItem (data, slicerId) {
      if (this.scriptItem.IsSlicer) {
        if (slicerId) {
          let arr = []
          this.slicerList.forEach(item => {
            arr = arr.concat(item.children)
          })
          let result = arr.find(item => {
            return item.id === slicerId
          })
          if (result) {
            data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = result.gadgetSetting[result.gadgetSetting.slicer.key]
            data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsDbType] = result.gadgetSetting.slicer.dbType
            data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = null
            data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = false
            data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsName] = result.name
          }
        } else {
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = []
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsDbType] = null
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = null
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = false
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsName] = null
        }
      }
    },
    currentChangeSlice (data, slicerItem) {
      if (this.scriptItem.IsSlicer) {
        if (slicerItem) {
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = [slicerItem]
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsDbType] = 'text'
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = slicerItem
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsId] = null
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = true
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsName] = slicerItem
        } else {
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = []
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsDbType] = null
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = false
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = false
          data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsName] = null
        }
      }
    },
    changeSlicerStatus (data, val) {
      if (!val) {
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsKey] = []
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsDbType] = null
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent] = null
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus] = false
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsName] = null
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsId] = null
        data[this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsIgnoreFilter] = false
      }
    },
    setKeyList (param) {
      if (Array.isArray(param)) {
        this.scriptItem[this.scriptItem.keyOptions] = param
      }
    },
    clearData () {
      this.dataForm[this.scriptItem.text] = JSON.parse(JSON.stringify(this.scriptItem.defaultValue))
    },
    optionsFilter (type, filterItem) {
      let options
      options = this.gadgetSetting.customRuleOptionList.filter(items => items['type'] === type)
      return options
    },
    changeHander (e, row) {
      if (e === 'in' || e === 'not in' || e === 'notIn') {
        if (row.type === 'datetime' || row.type === 'date') {
          this.$set(row, this.scriptItem.valueFields, '')
        } else {
          this.$set(row, this.scriptItem.valueFields, [])
        }
      } else {
        this.$set(row, this.scriptItem.valueFields, '')
      }
      this.$forceUpdate()
    },
    setType (e, row) {
      this.$set(row, this.scriptItem.optionFields, '')
      this.$set(row, this.scriptItem.valueFields, '')
      // this.$set(row, 'toObject', { disabled: false })
      const keyObj = this.scriptItem[this.scriptItem.keyOptions].find(item => item.value === row[this.scriptItem.keyFields])
      if (keyObj && keyObj.type) {
        this.$set(row, this.scriptItem.valueTypeFields, keyObj.type)
        if(this.nextTicketType === 'nextTicket') {
          this.$set(row, 'isCustomField', keyObj.isCustomField)
        }
      }
      this.$forceUpdate()
      // if (keyObj.toObject) {
      //   this.$set(row, 'toObject', keyObj.toObject)
      // }
      this.getValueList(e)
    },
    elRadioGroupChange () {
      this.$forceUpdate()
    },
    condition (type, parentIndex, index) {
      if (typeof parentIndex === 'undefined') {
        this.dataSource[this.scriptItem.text][this.scriptItem.condition] = type
      } else {
        this.dataSource[this.scriptItem.text][this.scriptItem.dataArr][parentIndex][this.scriptItem.dataArr][index][this.scriptItem.condition] = type
      }
    },
    changeAndOr (index, relation) {
      this.$set(this.dataSource[this.scriptItem.text], index, { ...this.dataSource[this.scriptItem.text][index], relation })
    },
    addRow (type, prentIndex) {
      this.addCondition = false
      if (type === 'row') {
        let row = this._.cloneDeep(this.scriptItem.defaultObject)
        this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].push({ ...row })
      } else {
        if (type === 'child') {
          let grp = this._.cloneDeep(this.scriptItem.defaultObject)
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr][prentIndex][this.scriptItem.dataArr].push({ ...grp })
        } else {
          let grpRow = this._.cloneDeep(this.scriptItem.defaultValue)
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].push({ ...grpRow })
        }
      }
      this.$forceUpdate()
    },
    deleteRow (thisIndex, type, prentIndex) {
      if (this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].length >= 1) {
        if (type === 'addData') {
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].splice(thisIndex, 1)
        } else {
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr][prentIndex][this.scriptItem.dataArr].splice(thisIndex, 1)
          if (this.dataSource[this.scriptItem.text][this.scriptItem.dataArr][prentIndex][this.scriptItem.dataArr].length === 0) {
            this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].splice(prentIndex, 1)
          }
        }
      }
      this.$forceUpdate()
    },
    checkValue (element, from) {
      let keys = Object.keys(element)
      let values = Object.values(element)
      let arrayName = this.scriptItem.dataArr
      if (keys.indexOf(arrayName) !== -1 && values.length > 0) {
        for (let index = 0; index < element[arrayName].length; index++) {
          if (Object.keys(element[arrayName][index]).indexOf(arrayName) !== -1) {
            return this.checkValue(element[arrayName][index])
          } else {
            let atomKey = Object.values(element[arrayName][index])
            let messageIndex = atomKey.findIndex(e => {
              if (typeof e === 'string') return !e
              if (Array.isArray(e)) return !(e.length > 0)
            })
            if (from) {
              if (atomKey[0] && messageIndex !== -1) {
                let hasEmpty = element[arrayName][index][this.scriptItem.optionFields] === 'is null'
                let ischanged = element[arrayName][index][this.scriptItem.optionFields] === 'changed'
                let hasnextTiketEmpty = element[arrayName][index][this.scriptItem.optionFields] === '=null'
                let hasNotEmpty = element[arrayName][index][this.scriptItem.optionFields] === 'is not null'
                let hasnextTiketNotEmpty = element[arrayName][index][this.scriptItem.optionFields] === '!=null'
                let hasBlank = element[arrayName][index][this.scriptItem.optionFields] === "=''"
                let hasNotBlank = element[arrayName][index][this.scriptItem.optionFields] === "!=''"
                let hasnotExist = element[arrayName][index][this.scriptItem.optionFields] === 'notExist'
                let hasExist = element[arrayName][index][this.scriptItem.optionFields] === 'exist'
                if (!hasEmpty && !hasNotEmpty && !hasBlank && !hasNotBlank && !hasnextTiketEmpty && !hasnextTiketNotEmpty && !hasExist && !hasnotExist && !ischanged) {
                  this.$message.error(Object.keys(element[arrayName][index])[messageIndex] + ' Is required.')
                  return false
                }
              }
            } else {
              if (messageIndex !== -1) {
                let hasEmpty = element[arrayName][index][this.scriptItem.optionFields] === 'is null'
                let ischanged = element[arrayName][index][this.scriptItem.optionFields] === 'changed'
                let hasnextTiketEmpty = element[arrayName][index][this.scriptItem.optionFields] === '=null'
                let hasNotEmpty = element[arrayName][index][this.scriptItem.optionFields] === 'is not null'
                let hasnextTiketNotEmpty = element[arrayName][index][this.scriptItem.optionFields] === '!=null'
                let hasBlank = element[arrayName][index][this.scriptItem.optionFields] === "=''"
                let hasNotBlank = element[arrayName][index][this.scriptItem.optionFields] === "!=''"
                let hasnotExist = element[arrayName][index][this.scriptItem.optionFields] === 'notExist'
                let hasExist = element[arrayName][index][this.scriptItem.optionFields] === 'exist'
                if (!hasEmpty && !hasNotEmpty && !hasBlank && !hasNotBlank && !hasnextTiketEmpty && !hasnextTiketNotEmpty && !hasExist && !hasnotExist && !ischanged) {
                  this.$message.error(Object.keys(element[arrayName][index])[messageIndex] + ' Is required.')
                  return false
                }
              }
            }
            let slicerStatus = this.scriptItem.IsSlicer ? element[arrayName][index][this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsStatus] : false
            if (slicerStatus) {
              let currentStatus = element[arrayName][index][this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrentStatus]
              let hasEmpty = element[arrayName][index][this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsId]
              let hasFieldsEmpty = element[arrayName][index][this.scriptItem.slicerFieldsObj][this.scriptItem.slicerFieldsCurrent]
              if (currentStatus) {
                if (!hasFieldsEmpty) {
                  this.$message.error('Slicer Is required.')
                  return false
                }
              } else {
                if (!hasEmpty) {
                  this.$message.error('Slicer Is required.')
                  return false
                }
              }
            }
          }
        }
      }
      return true
    },
    checkdataArr (from) {
      if (!this.checkValue(this.dataSource[this.scriptItem.text], from)) {
        return false
      } else {
        return true
      }
    },
    parseFilter () {
      if (this.checkdataArr()) {
        this.parseFilterLoading = true
        let sqlwhere = generalConvertJsonToSQL(this.dataSource[this.scriptItem.text])
        const params = {
          filter_sql: sqlwhere,
          datasetId: this.$store.state.typeFilterDatasetId
        }
        this.$interface.reports.parseFilterApi(params)
          .then(({ data: res }) => {
            this.parseFilterLoading = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.alertMessage(res.rawSql, res.executeSql)
          }).catch(() => {
            this.parseFilterLoading = false
          })
      }
    },
    clearFilter () {
      let temp = {}
      temp[this.scriptItem.dataArr] = []
      temp[this.scriptItem.condition] = 'and'
      this.dataForm[this.scriptItem.text] = temp
      // this.dataSource[this.scriptItem.text] = temp
      this.$emit('clearFilter', temp)
      this.clearAllPopover = false
    },
    alertMessage (filterExpression, filterSql) {
      const h = this.$createElement
      this.$msgbox({
        title: 'Parse Result',
        message: h('p', null, [
          h('p', null, [
            h('span', null, `Filter Expression: `),
            h('span', { style: 'color:#999999;' }, `${filterExpression}`)
          ]),
          h('p', null, [
            h('span', null, `Filter SQL: `),
            h('span', { style: 'color:#999999;' }, `${filterSql}`)
          ])
        ]),
        showCancelButton: true,
        showConfirmButton: false,
        cancelButtonText: 'Close'
      })
    },
    getSlicerInfoList () {
      this.$interface.reports.getIntegrationSlicerListApi({}).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        var temp = res.data.sort(function (a, b) {
          return a.name.localeCompare(b.name)
        })
        temp.forEach(it => {
          it.label = it.name
          it.value = it.id
          if (it.integration && it.integration.includes(',')) {
            it.integration = it.integration.split(',')
          } else if (!it.integration) {
            it.integration = it.integration
          } else {
            it.integration = [it.integration]
          }
        })
        temp.forEach(e => {
          if (!e.integration) {
            var has = this.slicerList.some(oo => {
              return oo.label === 'others'
            })
            if (!has) {
              this.slicerList.push({ label: 'others', value: 'zzzz', children: [] })
            }
          } else {
            e.integration.forEach(m => {
              var have = this.slicerList.some(o => {
                return o.label === m
              })
              if (!have) {
                this.slicerList.push({ label: m, value: m, children: [] })
              }
            })
          }
        })
        temp.forEach(item => {
          if (item.integration) {
            item.integration.forEach(n => {
              var inte = this.slicerList.find(its => {
                return its.label === n
              })
              inte.children.push(item)
            })
          } else {
            this.slicerList.find(i => {
              return i.label === 'others'
            }).children.push(item)
          }
        })
        this.slicerList = this.slicerList.sort(function (a, b) {
          return a.value.localeCompare(b.value)
        })
      }).catch(() => { })
    },
    waitDataSourceInit () {
      setTimeout(() => {
        if (this.dataSource[this.scriptItem.text] &&
          Array.isArray(this.dataSource[this.scriptItem.text][this.scriptItem.dataArr]) &&
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr].length > 0 &&
          this.dataSource[this.scriptItem.text][this.scriptItem.dataArr][0][this.scriptItem.keyFields]) {
          this.initValueList()
        } else {
          this.waitDataSourceInit()
        }
      }, 1000)
    },
    initValueList () {
      let tempList = []
      let valueList = []
      let data = this.dataSource[this.scriptItem.text]
      let outList = data[this.scriptItem.dataArr]
      Array.isArray(outList) && outList.length > 0 && outList.map(item => {
        let rules = item[this.scriptItem.dataArr]
        if (Array.isArray(rules)) {
          rules.length > 0 && rules.map(its => {
            tempList.push(its[this.scriptItem.keyFields])
            valueList.push(its[this.scriptItem.valueFields])
          })
        } else {
          tempList.push(item[this.scriptItem.keyFields])
          valueList.push(item[this.scriptItem.valueFields])
        }
      })
      this._.uniq(tempList).map((field, index) => {
        if (field === 'company/id') {
          this.getValueList(field, '', valueList[index])
        } else {
          this.getValueList(field)
        }
      })
    },
    getValueList (field, value, ids) {
      try {
        let res = this.gadgetSetting.customRuleKeyArray.find(i=>i.value === field)
        if(res&&res.url) {
            let params = {
              tenantCode: this.$store.state.user.tenantCode,
              // limit: 100,
              name: value || ''
            }
            this.$http.get(res.url,{params}).then(({data:res})=>{
              if (Array.isArray(res.data)) {
                try {
                  // if(this.nextTicketType==='jira') {
                    if(!this.isRemoteObject[field]) {
                      this.$set(this.isRemoteObject,field,res.data.length)
                    }
                  // }
                } catch (error) {
                  
                }
                this.$set(this.allValueList, field, res.data)
              }
            })
        } 
      } catch (error) {
        
      }
    },
    initBotOriginData (id, type) {
      this.originDataIdForBot = id
      this.originDataTypeForBot = type
    },
    changeValue: debounce(function (value, field) {
      this.getValueList(field, value)
    }, 500),
    remoteMethod (e) {
      this.changeValue(e, localStorage.getItem('tempFilterValue'))
    },
    setTempField (field) {
      localStorage.setItem('tempFilterValue', field)
    },
    clearTempField () {
      localStorage.removeItem('tempFilterValue')
    },
    valueIsOldData (value) {
      return Boolean(typeof value === 'string' && value.includes(','))
    },
    valueFieldDisabled (optionFields) {
      let isDisabled = false
      switch (optionFields) {
        case 'is null':
          isDisabled = true
          break
        case 'is not null':
          isDisabled = true
          break
        case "!=''":
          isDisabled = true
          break
        case "=''":
          isDisabled = true
          break
      }
      return isDisabled
    },
    getDataSource() {
      return this.dataSource
    },
    testHandlerForCustomRule() {
      this.$emit('testHandlerForCustomRule')
    },
  },
  // beforeDestroy () {
  //   this.$emit('update', this.dataSource)
  // },
  destroyed () {
    this.$root.eventBus.$off('filterPreviewDialogUpdateFilter')
  }
}
</script>

<style scoped lang='scss'>
.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  &-action-btn-group {
    width: 70px;
    height: 42px;
    vertical-align: baseline;
  }

  &-content {
    width: calc(100% - 180px);
    display: flex;
    align-items: center;

    &-form {
      display: flex;
      align-items: center;
      justify-content: space-evenly;

      .el-form-item .el-form-item {
        display: flex;
        align-items: center;
      }
    }
  }

  &-relation-btn-group {
    width: 110px;
    height: 42px;

    .el-button-group {
      vertical-align: baseline;
    }
  }
}
.parse-filter {
  position: absolute;
  right: 30px;
  top: 0;
}
.test {
  position: absolute;
  right: 30px;
  top: 0;
}
.clear-filter {
  position: absolute;
  right: 0;
  top: 0;
}
.hide-border {
  border: none;
}
.elcascader .el-cascader {
  line-height: 0 !important;
}

.item-line {
  position: relative;
  &::after {
    content: "";
    width: 20px;
    height: calc(100% - 1px);
    position: absolute;
    bottom: 50%;
    left: -20px;
    border-bottom: 1px dashed $--themt-color-border;
  }
  &::before {
    content: "";
    width: 1px;
    height: 8px;
    position: absolute;
    bottom: calc(50% - 4px);
    left: -1px;
    background: $--themt-color-border;
  }
}
.in-column-line {
  position: relative;
  margin-bottom: 10px;
  &::after {
    content: "";
    width: 20px;
    height: calc(100% - 12px);
    position: absolute;
    bottom: 24px;
    left: 10px;
    border-left: 1px dashed $--themt-color-border;
  }
}
.out-column-line {
  overflow-y: scroll;
  position: relative;
  max-height: 392px;
  &::after {
    content: "";
    width: 20px;
    height: calc(100% - 12px);
    position: absolute;
    bottom: 24px;
    left: 10px;
    border-left: 1px dashed $--themt-color-border;
    z-index: 1;
  }
}
.hide-out-column-line {
  position: relative;
  &::after {
    content: "";
    width: 20px;
    height: calc(100% - 24px);
    position: absolute;
    bottom: 0;
    left: -20px;
    border-left: 1px solid #ffffff;
    z-index: 2;
  }
}
.iconfont-normal {
  width: 28px;
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
}
.iconfont-normal-line {
  width: 28px;
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  cursor: pointer;
  &:hover {
    background-color: #d8d8d8;
  }
}
.header-item {
  border-top-left-radius: 4px !important;
  border-top-right-radius: 4px !important;
  border-bottom: 1px dashed #c1c1c1;
}
.center-item {
  border-radius: 0;
  border-bottom: 1px dashed #c1c1c1;
}
.footer-item {
  border-bottom-right-radius: 4px !important;
  border-bottom-left-radius: 4px !important;
  border-bottom: none;
}
.clear-all-css {
  padding: 7px 20px;
  background-color: red;
  color: #ffffff;
}
.add-group-item {
  padding: 9px 20px;
  cursor: pointer;
  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
}
</style>
<style lang="scss" scoped>
.filter-component {
  .el-radio-button__inner {
    padding: 5px 10px;
  }
   ::v-deep .el-tag.el-tag--info {
    max-width: none;
  }
}
.el-popover.filter-add-group-popover {
  padding: 10px 0;
}
</style>
